//
//  SpeechPlayHelper.swift
//  Pods
//
//  Created by HONOR on 2025/5/8.
//

import Flutter
import Foundation

class SpeechPlayHelper {
    private let TAG = "| SpeechPlayHelper | Flutter | iOS | "
    static let shared = SpeechPlayHelper()
    
    private init() {}
    
    private var dartIsReady = false
    private var channel: FlutterMethodChannel?
    
    func setMethodChannel(channel: FlutterMethodChannel) {
        self.channel = channel
    }
    
    func setDartIsReady(_ isReady: Bool) {
        dartIsReady = isReady
    }
    
    func onListenerCompleted() {
        guard dartIsReady else { return }
        
        let data: [String: Any] = ["code": "1"]
        runMainThread(data: data, method: "onListenerCompleted")
    }
    
    func onListenerPlayTime(time: Double) {
        guard dartIsReady else { return }
        
        let data: [String: Any] = ["time": time]
        runMainThread(data: data, method: "onListenerPlayTime")
    }
    
    func onSwitchSpeaker(status: Bool) {
        guard dartIsReady else { return }
        
        let data: [String: Any] = ["status": status]
        runMainThread(data: data, method: "onSwitchSpeaker")
    }
    
    private func runMainThread(data: [String: Any], method: String) {
        DispatchQueue.main.async { [weak self] in
            guard let channel = self?.channel else {
                print(self?.TAG ?? "" + "channel is null do nothing")
                return
            }
            
            channel.invokeMethod(method, arguments: data)
        }
    }
}
